package com.englisheveryday.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.Set;
import java.util.TreeMap;

import com.englisheveryday.constants.Constants;
import com.englisheveryday.utils.CodeSecretGenerator;
import com.englisheveryday.utils.L;

/**
 * <pre>
 *    用于和服务器通信
 * </pre>
 * @author 马永华
 * @date 2012-9-16 下午5:08:27
 * @version 1.1
 */

public class DefaultConnection {
	
	public static String appKey = "ff80808134fa25750134fa6825740008";
	public static String appSecret = "ff80808134fa25750134fa3ab4650006";
	private static String url = Constants.URL+"router";
	
	//同步每日口语
	public String sync_article(String lastAnchor,String nextAnchor){
		System.out.println(lastAnchor);
		System.out.println(nextAnchor);
		TreeMap<String,String> map = new TreeMap<String,String>();
		map.put("appKey", appKey);
		map.put("version", "1.0");
		map.put("format", "JSON");
		map.put("timestamp", "2012-12-1");
		map.put("method", "com.englisheveryday.article.sync");
		map.put("lastAnchor",lastAnchor);
		map.put("nextAnchor", nextAnchor);
		map.put("sign", sign(map));
		return sendData(map,url);
	}
	
	//同步类别
	public String sync_category(String lastAnchor,String nextAnchor){
		System.out.println(lastAnchor);
		System.out.println(nextAnchor);
		TreeMap<String,String> map = new TreeMap<String,String>();
		map.put("appKey", appKey);
		map.put("version", "1.0");
		map.put("format", "JSON");
		map.put("timestamp", "2012-12-1");
		map.put("method", "com.englisheveryday.category.sync");
		map.put("lastAnchor",lastAnchor);
		map.put("nextAnchor", nextAnchor);
		map.put("sign", sign(map));
		return sendData(map,url);
	}
	
	
	//提交用户反馈
	public String feedback(String content){
		TreeMap<String,String> map = new TreeMap<String,String>();
		map.put("appKey", appKey);
		map.put("version", "1.0");
		map.put("format", "JSON");
		map.put("timestamp", "2012-12-1");
		map.put("method", "com.englisheveryday.feedback.add");
		map.put("content",content);
		map.put("sign", sign(map));
		return sendData(map,url);
	}
	
	//检查系统更新
	public String checkupdate(){
		TreeMap<String,String> map = new TreeMap<String,String>();
		map.put("appKey", appKey);
		map.put("version", "1.0");
		map.put("format", "JSON");
		map.put("timestamp", "2012-12-1");
		map.put("method", "com.englisheveryday.systemupdate.get");
		map.put("sign", sign(map));
		return sendData(map,url);
	}
	
	
	String sendData(TreeMap map,String address){
		HttpURLConnection connection = null;
		BufferedReader bis = null;
		OutputStream os = null;
		String returnData = "";
		System.out.println(address);
		try{
			URL url = new URL(address);
		    connection = (HttpURLConnection)url.openConnection();
			connection.setRequestMethod("GET");
			String paramter = mapToString(map,"UTF-8");
			connection.setConnectTimeout(20*1000);
			connection.setReadTimeout(20*1000);
			connection.setDoOutput(true);
			connection.connect();
			os = connection.getOutputStream();
			os.write(paramter.getBytes("UTF-8"));
			os.flush();
			if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
				bis = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
				String str = "";
				while((str=bis.readLine())!=null){
					returnData+=str;
				}
				System.out.println(returnData);
			}
			
		}catch(SocketTimeoutException e){
			e.printStackTrace();
			L.d("超时");
			return Constants.SYNC_STATUS_READTIMEOUT;
		}catch(IOException e){
			e.printStackTrace();
			return Constants.SYNC_STATUS_FAILURE;
		}finally{
			if(connection!=null){
				connection.disconnect();
			}
			if(bis!=null){
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(os!=null){
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
		return returnData;
	}
	//把Map转换为String
	 String mapToString(TreeMap<String,String> map,String charset){
		Set<String> set = map.keySet();
		StringBuilder sb = new StringBuilder();
		if(map!=null&&set.size()>0){
			for(String str:set){
				sb.append(str).append("=").append(map.get(str)).append("&");
			}
		}
		return sb.toString();
	}
	
	 //签名
	 String sign(TreeMap<String,String> map){
		StringBuilder sb = new StringBuilder();
		Set<String> set = map.keySet();
		sb.append(appSecret);
		for(String key:set){
			sb.append(key).append(map.get(key));
		}
		String str = "";
		try {
			str = new String(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return CodeSecretGenerator.getDigestSHA(str).toUpperCase();
	}

}

